package custom;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dd.CircularProgressButton;
import com.example.menhoo.menhoolibrary.R;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.AndroidFileUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.io.FileUtils;
import com.example.menhoo.toollibrary.common.utils.AndroidUtil;
import com.example.menhoo.toollibrary.common.utils.SdCardUtil;
import com.example.menhoo.toollibrary.common.utils.VibrateUtil;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.cache.MD5FileNameGenerator;
import com.lidroid.xutils.util.LogUtils;
import com.rey.material.widget.ProgressView;
import com.rey.material.widget.Slider;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import application.UIApplication;
import application.UIHttpURL;
import frame.UIActivity;
import interfaces.IDownLoadListener;
import model.DownloadDbModel;
import model.FileInfo;
import model.ImageInfo;
import service.DownLoadService;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * 竖着的 更适合文档浏览
 * Created by yanglei on 15/11/5.
 */
public class ScaleDocImageActivity extends UIActivity {

    public class ScalePageModel {
        public int Page;
        public String Name;
        public String Url;
        public boolean isSelect = false;
    }

    /**
     * 是否显示标题栏的标识变量
     */
    boolean F = true;

    DrawerLayout main_dl;
    LinearLayout linearLayoutMainPage, linearLayoutTitlebar, linearLayoutSlider,titlebar_layout_custom_cnx;
    ListView listViewContent;
    ListView listViewPages;
    FrameLayout main_fl_drawer;

    //
    TextView titlebar_tv_title_text, titlebar_tv_title_subtext, textViewPagesTotal;
    ImageButton titlebar_btn_back;
    Slider sl_discrete;

    List<String> urlList;
    List<ScalePageModel> pagesList;
    int DocPages, CurrPage = 1;

    DocAdapter docAdapter;

    private FileInfo fileInfo=null;
    private ImageInfo imageInfo=null;

    @Override
    public void beforeOnCreate() {
        super.beforeOnCreate();
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            fileInfo=(FileInfo)getIntent().getExtras().getSerializable("fileInfo");
//            fileInfo.downloadUrl = UIHttpURL.getWebSiteFullUrl(fileInfo.downloadUrl);
//            fileInfo.thumbUrl = UIHttpURL.getWebSiteFullUrl(fileInfo.thumbUrl);
        }
        catch (Exception e){}
        try{
            imageInfo=(ImageInfo)getIntent().getExtras().getSerializable("imageInfo");
        }
        catch (Exception e){
            MessageUtil.showShortToast(this,"打开文档失败");
            onBackPressed();
        }
        try {
            DocPages = imageInfo.urls.length;
            urlList = new ArrayList<String>();
            pagesList = new ArrayList<ScalePageModel>();
            for (int i = 0; i < imageInfo.urls.length; i++) {
                String sUrl = imageInfo.urls[i];
                urlList.add(sUrl);

                ScalePageModel spm = new ScalePageModel();
                spm.Page = i + 1;
                spm.Name = imageInfo.title;
                spm.Url = sUrl;
                pagesList.add(spm);
            }
        } catch (Exception e) {
            finish();
        }

        try {
            CurrPage = imageInfo.curIndex;
            if (CurrPage > DocPages) {
                CurrPage = DocPages;
            } else if (CurrPage <= 0) {
                CurrPage = 1;
            }
        } catch (Exception e) {
            CurrPage = 1;
        }
        if(imageInfo!=null){
            try
            {
                CurrPage=imageInfo.curIndex;
                if(CurrPage>DocPages){
                    CurrPage=DocPages;
                }
                else if(CurrPage<=0){
                    CurrPage=1;
                }
            }
            catch (Exception e) {
                CurrPage=1;
            }
        }

        setContentView(R.layout.activity_scale_doc_images);

        setTitleDisplay(false);

        titlebar_layout_custom_cnx=(LinearLayout)findViewById(R.id.titlebar_layout_custom_cnx);
        sl_discrete = (Slider) findViewById(R.id.slider_sl_discrete);
        if (DocPages > 1) {
            sl_discrete.setValueRange(1, DocPages, false);
            sl_discrete.setValue(1, false);
            sl_discrete.setOnPositionChangeListener(new Slider.OnPositionChangeListener() {
                @Override
                public void onPositionChanged(Slider view, boolean fromUser, float oldPos, float newPos, int oldValue, int
                        newValue) {

                    try {
                        if (CurrPage == newValue) {
                            return;
                        }

                        if (newValue <= 0) {
                            try {
                                sl_discrete.setValue(1, false);
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }

                            CurrPage = 1;
                        } else {
                            CurrPage = newValue;

                        }
                        if (docAdapter != null) {
                            listViewContent.setSelection(CurrPage - 1);
                        }
                    } catch (Exception e) {
                        LogUtils.e(e.getMessage() + "");
                    }


                }
            });
        } else {

        }

        main_dl = (DrawerLayout) findViewById(R.id.main_dl);
        main_fl_drawer = (FrameLayout) findViewById(R.id.main_fl_drawer);

        textViewPagesTotal = (TextView) findViewById(R.id.textViewPagesTotal);
        textViewPagesTotal.setText(DocPages + "");
        titlebar_tv_title_text = (TextView) findViewById(R.id.titlebar_tv_title_text);
        titlebar_tv_title_text.setText(imageInfo.title == null ? "" : imageInfo.title);
        titlebar_tv_title_subtext = (TextView) findViewById(R.id.titlebar_tv_title_subtext);
        titlebar_tv_title_subtext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        titlebar_btn_back = (ImageButton) findViewById(R.id.titlebar_btn_back);
        titlebar_btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VibrateUtil.vibrateShot(ScaleDocImageActivity.this);
                onBackPressed();
            }
        });

        linearLayoutMainPage = (LinearLayout) findViewById(R.id.linearLayoutMainPage);
        linearLayoutTitlebar = (LinearLayout) findViewById(R.id.linearLayoutTitlebar);
        linearLayoutSlider = (LinearLayout) findViewById(R.id.linearLayoutSlider);

        if (DocPages > 1) {
            linearLayoutSlider.setVisibility(View.VISIBLE);
        } else {
            linearLayoutSlider.setVisibility(View.GONE);
        }

        //
        listViewContent = (ListView) findViewById(R.id.listViewContent);
        listViewPages = (ListView) findViewById(R.id.listViewPages);
        listViewContent.setOnScrollListener(new PauseOnScrollListener(getBitmapLoader(), true, true, new AbsListView
                .OnScrollListener() {


            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                CurrPage = firstVisibleItem + 1;
                sl_discrete.setValue(CurrPage, true);
                titlebar_tv_title_subtext.setText("");
            }
        }));

        docAdapter = new DocAdapter(pagesList);
        listViewContent.setAdapter(docAdapter);
        //禁用滑动边框
        main_dl.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

    }

    public FileInfo getFileInfo() {
        return fileInfo;
    }

    public ImageInfo getImageInfo() {
        return imageInfo;
    }

    /**
     * 得到自定义右边按钮
     * @return
     */
    public LinearLayout getRightCustom(){
        return titlebar_layout_custom_cnx;
    }

    @Override
    public void onBackPressed() {
        main_dl.closeDrawer(main_fl_drawer);
        super.onBackPressed();
        overridePendingTransition(R.anim.anim_scale_in, R.anim.anim_scale_out);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    class DocAdapter extends BaseAdapter {
        List<ScalePageModel> data = null;

        public DocAdapter() {
            this.data = new ArrayList<ScalePageModel>();
        }

        public DocAdapter(List<ScalePageModel> data) {
            this.data = data;
        }

        public void add(List<ScalePageModel> data) {
            if (this.data != null) {
                this.data.addAll(data);
                notifyDataSetChanged();
            }
        }

        @Override
        public int getCount() {
            if (this.data != null) {
                return this.data.size();
            } else {
                return 0;
            }

        }

        public void selectItme(int position) {

            for (ScalePageModel spm : data) {
                spm.isSelect = false;

                if (spm.Page - 1 == position) {
                    spm.isSelect = true;
                }
            }
            notifyDataSetChanged();
            return;
        }

        @Override
        public ScalePageModel getItem(int position) {
            if (this.data != null) {
                return this.data.get(position);
            } else {
                return null;
            }

        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void displayImage(final String url, final PhotoView photoView, final ProgressView progressBanner, final
        LinearLayout linearLayoutError, final RelativeLayout linearLayoutRoot) {


            getBitmapLoader().display(photoView, url, new BitmapLoadCallBack<PhotoView>() {
                @Override
                public void onLoadCompleted(PhotoView container, String s, Bitmap bitmap, BitmapDisplayConfig
                        bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {

                    try {
                        progressBanner.stop();
                    } catch (Exception e) {
                        LogUtils.e(e.getMessage() + "");
                    }

                    progressBanner.setVisibility(View.GONE);
                    linearLayoutError.setVisibility(View.GONE);
                    container.setVisibility(View.VISIBLE);
                    container.setImageBitmap(bitmap);

//                    int bitmapWidth = bitmap.getWidth();
//                    int bitmapHeight = bitmap.getHeight();
//                    float bitmapFloat = Float.parseFloat(bitmapHeight + "") / bitmapWidth;
//                    int screenWidth = getResources().getDisplayMetrics().widthPixels;
//                    int screenHeight = getResources().getDisplayMetrics().heightPixels;
//                    //设置图片尺寸
//                    ViewGroup.LayoutParams layoutParams = container.getLayoutParams();
//                    layoutParams.width = screenWidth;
//                    layoutParams.height = (int) (screenWidth * bitmapFloat);
//                    container.setLayoutParams(layoutParams);


                    container.clearAnimation();
                    container.startAnimation(UIApplication.getAnimationSet());

                    container.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            VibrateUtil.vibrateShot(ScaleDocImageActivity.this);
                            final android.app.Dialog dialog = showSimpleCustomDialogMessage(R.layout.scale_images_dialog, false);
                            if (dialog != null) {
                                com.rey.material.widget.Button buttonCallPhone = (com.rey.material.widget.Button) dialog
                                        .findViewById(R.id.buttonSaveImage);
                                buttonCallPhone.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //保存图片
//
                                        String path = SdCardUtil.getSdDCIMCamera() + new MD5FileNameGenerator().generate(url) +
                                                ".jpg";
                                        try {
                                            File srcFile = getBitmapLoader().getBitmapFileFromDiskCache(url);
                                            File toFile = new File(path);
                                            if (toFile.exists()) {
                                                MessageUtil.showShortToast(ScaleDocImageActivity.this, "已经下载过此项");
                                            } else {
                                                FileUtils.copyFile(srcFile, toFile);
                                                MessageUtil.showShortToast(ScaleDocImageActivity.this, "保存到:" + path);
                                            }

                                        } catch (Exception e) {
                                            LogUtils.e(e.getMessage() + "");
                                            MessageUtil.showShortToast(ScaleDocImageActivity.this, "保存失败");
                                        }

                                        //
                                        dialog.dismiss();
                                    }
                                });


                                com.rey.material.widget.Button buttonCancel = (com.rey.material.widget.Button) dialog
                                        .findViewById(R.id.buttonCancel);
                                buttonCancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                            }
                            return false;
                        }
                    });
                }

                @Override
                public void onLoadFailed(PhotoView container, String s, Drawable drawable) {
                    LogUtils.e(s + "");
                    try {
                        progressBanner.stop();
                    } catch (Exception e) {
                        LogUtils.e(e.getMessage() + "");
                    }

                    progressBanner.setVisibility(View.GONE);
                    container.setVisibility(View.GONE);
                    linearLayoutError.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadStarted(PhotoView container, String uri, BitmapDisplayConfig config) {
                    super.onLoadStarted(container, uri, config);
                    try {
                        progressBanner.setProgress(0.2f);
                        progressBanner.start();
                    } catch (Exception e) {
                        LogUtils.e(e.getMessage() + "");
                    }

                    progressBanner.setVisibility(View.VISIBLE);
                    container.setVisibility(View.GONE);
                    linearLayoutError.setVisibility(View.GONE);
                }

                @Override
                public void onLoading(PhotoView container, String uri, BitmapDisplayConfig config, long total, long current) {
                    super.onLoading(container, uri, config, total, current);
                    try {
                        float percent = ((float) current) / total;
                        if (percent < 0.2) {
                            progressBanner.setProgress(percent);
                        }
                        //LogUtils.e("百分百:"+percent+"%");
                    } catch (Exception e) {
                        LogUtils.e(e.getMessage() + "");
                    }

                    progressBanner.setVisibility(View.VISIBLE);
                    container.setVisibility(View.GONE);
                    linearLayoutError.setVisibility(View.GONE);
                }

            });

        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.activity_scale_doc_images_item, null);
            }

            final ScalePageModel model = getItem(position);
            LinearLayout linearLayoutPage = (LinearLayout) convertView.findViewById(R.id.linearLayoutPage);
            final RelativeLayout relativeLayoutRoot = (RelativeLayout) convertView.findViewById(R.id.relativeLayoutRoot);
            TextView textViewPage = (TextView) convertView.findViewById(R.id.textViewPage);

            textViewPage.setText(model.Page + "");

            final PhotoView photoView = (PhotoView) convertView.findViewById(R.id.imageView);
            photoView.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                @Override
                public void onViewTap(View view, float x, float y) {
                    F = !F;
                    if (F) {
                        linearLayoutTitlebar.setVisibility(View.VISIBLE);
                        if (DocPages > 1) {
                            linearLayoutSlider.setVisibility(View.VISIBLE);
                        }
                        //linearLayoutMainPage.setBackgroundColor(getResources().getColor(R.color.transparent));
                    } else {
                        linearLayoutTitlebar.setVisibility(View.GONE);
                        linearLayoutSlider.setVisibility(View.GONE);
                        //linearLayoutMainPage.setBackgroundColor(getResources().getColor(R.color.black));
                    }
                    //MessageUtil.showSingletonToast(ScaleDocImageActivity.this,"x="+x+" :: y="+y);
                }
            });

            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            int screenHeight = getResources().getDisplayMetrics().heightPixels;
            //设置图片尺寸
            ViewGroup.LayoutParams layoutParams = photoView.getLayoutParams();
            layoutParams.width = screenWidth;
            layoutParams.height = (int) Math.ceil((double) (screenWidth * 1.4f));
            photoView.setLayoutParams(layoutParams);
            photoView.setMaxWidth(screenWidth);
            photoView.setMaxHeight(screenWidth * 15);
            photoView.setMinimumWidth(screenWidth);
            photoView.setMinimumHeight((int) Math.ceil((double) (screenWidth * 1.4f)));
            photoView.setIsVertical(true);//判断条件为竖着滑动

            //父窗体尺寸
            relativeLayoutRoot.setMinimumWidth(screenWidth);
            relativeLayoutRoot.setMinimumHeight((int) Math.ceil((double) (screenWidth * 1.4f)));

            final ProgressView progressBanner = (ProgressView) convertView.findViewById(R.id.progressBanner);
            final LinearLayout linearLayoutError = (LinearLayout) convertView.findViewById(R.id.linearLayoutError);
            final Button buttonError = (Button) convertView.findViewById(R.id.buttonError);
            buttonError.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String, String> map = new HashMap();
                    map.put("androidTime", new Date().getTime() + "");

                    displayImage(UIHttpURL.getWebSiteFullUrl(model.Url, map), photoView, progressBanner, linearLayoutError,
                            relativeLayoutRoot);
                }
            });

            displayImage(UIHttpURL.getWebSiteFullUrl(model.Url), photoView, progressBanner, linearLayoutError,
                    relativeLayoutRoot);


            return convertView;
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            titlebar_tv_title_text.setMaxWidth(AndroidUtil.dp2px(this, 550));
        } else {
            titlebar_tv_title_text.setMaxWidth(AndroidUtil.dp2px(this, 240));
        }


        if (this.docAdapter != null) {
            docAdapter.notifyDataSetChanged();
        }
    }
}
